package com.kexun;

import java.util.HashSet;
import java.util.Objects;

public class HashSetDemo2 {
    public static void main(String[] args) {
        // 创建集合对象
        HashSet<Studentdemo> hs = new HashSet<Studentdemo>();

        // 创建学生对象
        Studentdemo s1 = new Studentdemo("林青霞", 27);
        Studentdemo s2 = new Studentdemo("柳岩", 22);
        Studentdemo s3 = new Studentdemo("王祖贤", 30);
        Studentdemo s4 = new Studentdemo("林青霞", 27);
        Studentdemo s5 = new Studentdemo("林青霞", 20);
        Studentdemo s6 = new Studentdemo("范冰冰", 22);

        // 添加元素
        hs.add(s1);
        hs.add(s2);
        hs.add(s3);
        hs.add(s4);
        hs.add(s5);
        hs.add(s6);

        // 遍历集合
        for (Studentdemo s : hs) {
            System.out.println(s.getName() + "---" + s.getAge());
        }
    }

}
class Studentdemo{
    private String name;
    private int age;

    public Studentdemo() {
        super();
    }


    public Studentdemo(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Studentdemo that = (Studentdemo) o;
        return age == that.age &&
                Objects.equals(name, that.name);
    }


    //如果不重写hashcode()方法,默认调用Object类的hashcode()方法,比较的是对象的地址,即使内容相同 ,对象不同 ,集合会重复
    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }
}
